﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using System.Xml;
using System.Windows.Navigation;
using System.Xml.Linq;
using System.Diagnostics;
using Microsoft.Phone.Tasks;
using System.Runtime.Serialization.Json;
namespace OpenGovernment
{
    public partial class Page1 : PhoneApplicationPage
    {
        string url2;
        HttpWebRequest req;
        // Constructor
        public Page1()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            url2 = "http://opendata.diavgeia.gov.gr/api/decisions?";
            try
            {
                url2 += "type=" + NavigationContext.QueryString["type"] + "&";
            }
            catch (KeyNotFoundException) { }
            try
            {
                url2 += "signer=" + NavigationContext.QueryString["signer"] + "&";
            }
            catch (KeyNotFoundException) { }
            try
            {
                url2 += "datefrom=" + NavigationContext.QueryString["datefrom"] + "&";
            }
            catch (KeyNotFoundException) { }
            try
            {
                url2 += "dateto=" + NavigationContext.QueryString["dateto"] + "&";
            }
            catch (KeyNotFoundException) { }
            try
            {
                url2 += "tag=" + NavigationContext.QueryString["tag"] + "&";
            }
            catch (KeyNotFoundException) { }
            try
            {
                url2 += "org=" + NavigationContext.QueryString["org"] + "&";
            }
            catch (KeyNotFoundException) { }
            url2 += "output=json&count=25";
            req = (HttpWebRequest)WebRequest.Create(url2);
            req.BeginGetResponse(new AsyncCallback(RequestCallback), null);
        }
        
        void RequestCallback(IAsyncResult resu)
        {
            HttpWebResponse res;
            try
            {
                res = (HttpWebResponse)req.EndGetResponse(resu);
            }
            catch (WebException)
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    bar.IsIndeterminate = false;
                })); 
                return;
            }
            Thread.CurrentThread.CurrentCulture =
                new System.Globalization.CultureInfo("el-GR");

            //XmlReaderSettings xmlrs = 
            //    new XmlReaderSettings()
            //    { DtdProcessing = System.Xml.DtdProcessing.Ignore };
            //XmlReader xmlreader = XmlReader.Create(res.GetResponseStream(), xmlrs);
            //xmlreader.MoveToContent();

            Dispatcher.BeginInvoke(new Action(() =>
            {
                bar.IsIndeterminate = false;
            }));

            //XNamespace ns2 = "http://diavgeia.gov.gr/schema/api/diavgeia-decision-0.1";
            //XNamespace ns3 = "http://diavgeia.gov.gr/schema/model/diavgeia-decision-0.1";

            //XElement xe = (XElement)XElement.ReadFrom(xmlreader);
            ////get the latest updates
            
            var obj = new DataContractJsonSerializer(typeof(RootObject)).ReadObject(res.GetResponseStream());
            var model = ((RootObject)obj).model;
            var decisions = model.decisions;
            var list = new List<Update>();
            foreach (var y in decisions)
            {
                var money = "";
                try
                {
                    money = "Ποσό: " + y.metadata.extraFields.extraField.Single(x => x.name == "poso_dapanis").value + " ευρό";
                }
                catch { }
                list.Add(new Update()
                {
                    Subject = y.metadata.subject,
                    DocumentUrl = y.documentUrl,
                    Url = y.url,
                    amount = money
                });
            }

            Dispatcher.BeginInvoke(new Action(() => listBox1.ItemsSource = list));
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string url = (string)(sender as Button).Tag;
            WebBrowserTask task = new WebBrowserTask();
            task.Uri = new Uri(url);
            task.Show();
        }
    }

    public class Update
    {
        public string Subject { get; set; }
        public string DocumentUrl { get; set; }
        public string Url { get; set; }
        public string amount { get; set; }
    }

}
   